<script setup lang="ts">
import { h, onMounted, ref } from 'vue'
import { Button } from 'ant-design-vue'
import { dictTypeApi } from '@/api/sys/dictTypeApi'
import type { TreeItem } from '@/components/Tree'
import { BasicTree } from '@/components/Tree'
import DictTypeModal from '@/views/sys/dict/DictTypeModal.vue'
import { useModal } from '@/components/Modal'
import { useMessage } from '@/hooks/web/useMessage'
import { DictTypeComponentCodes } from '@/enums/componentCodesEnum'

defineOptions({ name: 'DictTypeTree' })
const emit = defineEmits(['select'])
const treeRef = ref()
const treeData = ref<TreeItem[]>([])

const [registerDictTypeModal, { openModal: openDictTypeModal }] = useModal()

async function fetch() {
  treeData.value = (await dictTypeApi.tree()).rows
}

function handleSelect(keys) {
  emit('select', keys[0])
}

function handleAdd() {
  openDictTypeModal(true, { isUpdate: false })
}

function handleUpdate(record: Recordable) {
  openDictTypeModal(true, { record, isUpdate: true })
}

const { createConfirm } = useMessage()

async function handleDelete(record: Recordable) {
  const { dictTypeId } = record

  return new Promise((resolve) => {
    createConfirm({
      title: '删除',
      content: `确定？`,
      iconType: 'warning',
      onOk: async () => {
        await dictTypeApi.delete({ dictTypeId })
        emit('select', '')
        fetch()
        return resolve(true)
      },
      onCancel: () => resolve(false),
    })
  })
}

onMounted(() => {
  fetch()
})
</script>

<template>
  <div class="m-4 mr-0 overflow-hidden" v-bind="$attrs">
    <div
      style="
        background: var(--component-background);
        margin-bottom: 10px;
        padding: 10px;
        text-align: right;
      "
    >
      <Button v-permission="DictTypeComponentCodes.Add" type="primary" @click="handleAdd">
        新增类型
      </Button>
    </div>
    <BasicTree
      ref="treeRef"
      title="字典类型列表"
      toolbar
      search
      tree-wrapper-class-name="h-[calc(100%-35px)] overflow-auto"
      :click-row-to-expand="false"
      :tree-data="treeData"
      :field-names="{ key: 'dictTypeId', title: 'title' }"
      :action-list="[
        {
          // TODO
          permission: DictTypeComponentCodes.Update,
          render(record) {
            return h(
              'a',
              {
                style: { marginRight: '20px' },
                onClick: handleUpdate.bind(null, record),
              },
              '更新',
            );
          },
        },
        {
          permission: DictTypeComponentCodes.Delete,
          render(record) {
            return h(
              'a',
              {
                style: { marginRight: '20px' },
                onClick: handleDelete.bind(null, record),
              },
              '删除',
            );
          },
        },
      ]"
      @select="handleSelect"
    />
    <DictTypeModal @register="registerDictTypeModal" @success="fetch" />
  </div>
</template>
